package priv.bestbeat.cloud.api.gateway.utils;

import com.fasterxml.jackson.core.JsonProcessingException;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpResponse;
import priv.bestbeat.cloud.common.exceptions.SystemRunningException;
import priv.bestbeat.cloud.common.utils.JacksonUtil;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;

/**
 * 响应式服务器HTTP工具类
 * @author 张渠钦
 * @date 2021/12/8 16:51
 */
public final class ReactiveServerHttpUtil {

    /**
     * 发送Mono消息
     * @param response
     * @param data
     * @param <T>
     * @return
     */
    public static <T> Mono<Void> sendMono(ServerHttpResponse response, T data)  {
        try {
            byte[] bytes = JacksonUtil.commonJackson().writeValueAsString(data).getBytes(StandardCharsets.UTF_8);
            DataBuffer dataBuffer = response.bufferFactory().wrap(bytes);
            response.getHeaders().setContentLength(bytes.length);
            response.getHeaders().setContentType(MediaType.APPLICATION_JSON);
            return response.writeAndFlushWith(Mono.just(Mono.just(dataBuffer)));
        } catch (JsonProcessingException e) {
            throw new SystemRunningException(e);
        }

    }

}
